package com.wanghua.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.wanghua.common.utils.R;
import com.wanghua.mall.cart.constant.CartConstant;
import com.wanghua.mall.cart.interceptor.CartInterceptor;
import com.wanghua.mall.cart.openfeign.ProductClient;
import com.wanghua.mall.cart.service.CartService;
import com.wanghua.mall.cart.vo.CartItemVo;
import com.wanghua.mall.cart.vo.CartVo;
import com.wanghua.mall.cart.vo.SkuInfoVo;
import com.wanghua.mall.cart.vo.UserInfoTo;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author wanghua
 * @create 2021-09-06 17:04
 */
@Service
public class CartServiceImpl implements CartService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ProductClient productClient;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 添加商品到购物车，存在放Redis中
     *
     * @param skuId 商品id
     * @param num   商品数量
     * @return
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        CartItemVo cartItemVo;
        //先检查购物车里是否有这个商品
        String jsonString = (String) cartOperations.get(skuId.toString());
        if (StringUtils.hasLength(jsonString)) {
            cartItemVo = JSON.parseObject(jsonString, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            cartOperations.delete(skuId.toString());
            cartOperations.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
        cartItemVo = new CartItemVo();
        //1.远程查询sku信息
        CompletableFuture<Void> getSkuInfoCompletableFuture = CompletableFuture.runAsync(() -> {
            String skuInfoVoString = productClient.skuInfo(skuId);
            SkuInfoVo skuInfoVo = JSON.parseObject(skuInfoVoString, SkuInfoVo.class);
            cartItemVo.setTitle(skuInfoVo.getSkuTitle());
            cartItemVo.setPrice(skuInfoVo.getPrice());
            cartItemVo.setCount(num);
            cartItemVo.setImage(skuInfoVo.getSkuDefaultImg());
            cartItemVo.setSkuId(skuId);
        }, threadPoolExecutor);

        CompletableFuture<Void> getSkuAttrCompletableFuture = CompletableFuture.runAsync(() -> {
            List<String> skuAttr = productClient.getSkuAttr(skuId);
            cartItemVo.setSkuAttr(skuAttr);
        }, threadPoolExecutor);

        try {
            CompletableFuture.allOf(getSkuInfoCompletableFuture, getSkuAttrCompletableFuture).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //给Redis保存cartItemVo
        jsonString = JSON.toJSONString(cartItemVo);
        cartOperations.put(skuId.toString(), jsonString);

        return cartItemVo;
    }

    /**
     * 获取购物车中的商品
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        String jsonString = (String) cartOperations.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(jsonString, CartItemVo.class);
        return cartItemVo;

    }

    /**
     * 获取购物车
     *
     * @return
     */
    @Override
    public CartVo getCart() {
        CartVo cartVo = new CartVo();

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        if (userInfoTo.getUserId() == null) {
            //未登录状态
            cartVo.setItems(getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserKey()));
        } else {
            //登陆状态
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            //获取临时购物车数据项
            String tempCartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null && tempCartItems.size() > 0) {
                //需要合并购物车
                tempCartItems.forEach((item) -> addToCart(item.getSkuId(), item.getCount()));
            }
            //清空临时购物车
            clearCart(tempCartKey);
            //包含临时购物车数据
            cartVo.setItems(getCartItems(cartKey));
        }
        return cartVo;
    }

    /**
     * 清空购物车，不指定cartKey
     */
    @Override
    public void clearCart() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        clearCart(cartKey);
    }

    /**
     * 选中购物车中商品
     *
     * @param skuId 商品id
     * @param check 商品之前是否被选中，1-选中，0-未选中
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItemVo cartItemVo = getCartItem(skuId);
        cartItemVo.setCheck(check == 1);
        getCartOperations().put(skuId.toString(), JSON.toJSONString(cartItemVo));
    }

    /**
     * 改变购物车中商品数量
     *
     * @param skuId 商品id
     * @param num   商品数量
     */
    @Override
    public void countItem(Long skuId, Integer num) {
        CartItemVo cartItemVo = getCartItem(skuId);
        cartItemVo.setCount(cartItemVo.getCount() + num);
        getCartOperations().put(skuId.toString(), JSON.toJSONString(cartItemVo));
    }

    /**
     * 删除购物车中商品
     *
     * @param skuId 商品id
     */
    @Override
    public void deleteItem(Long skuId) {
        getCartOperations().delete(skuId.toString());
    }

    /**
     * 获取当前用户在购物车中选中的购物项
     *
     * @return
     */
    @Override
    public List<CartItemVo> getCheckedItemsByUser() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItemVoList = getCartItems(cartKey);
            if (cartItemVoList != null && cartItemVoList.size() > 0) {
                //得到被选中的购物项
                return cartItemVoList.stream().filter(CartItemVo::getCheck).map((item) -> {
                    //设置最新价格
                    R r = productClient.getPriceBySkuId(item.getSkuId());
                    String price = (String) r.get("price");
                    item.setPrice(new BigDecimal(price));
                    return item;
                }).collect(Collectors.toList());
            }
        }
        return null;
    }

    /**
     * 清空购物车，指定cartKey
     */
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    /**
     * 获取操作Redis Hash的BoundHashOperations
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOperations() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        return stringRedisTemplate.boundHashOps(cartKey);
    }

    /**
     * 获取指定key购物车的商品
     *
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> cartOperations = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOperations.values();
        if (values != null && values.size() > 0) {
            return values.stream().map(item -> JSON.parseObject((String) item, CartItemVo.class)).collect(Collectors.toList());
        }
        return null;
    }
}
